package org.streets.eis.setting.converters;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Locale;

import org.apache.wicket.util.convert.converters.AbstractConverter;
import org.apache.wicket.util.string.Strings;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

public class SqlTimeConverter extends AbstractConverter {
	private static final long serialVersionUID = 1L;

	private String pattern = "HH:mm:ss";
	
	public SqlTimeConverter(){
	}
	
	public SqlTimeConverter(String pattern){
		this.pattern = pattern;
	}
	
	public Time convertToObject(String value, Locale locale){
		if (Strings.isEmpty(value)){
			return null;
		}
		try{
			java.util.Date date = DateTimeFormat.forPattern(pattern).parseDateTime(value).toDate();
			return new Time(date.getTime());
		}catch(Exception e){
			throw newConversionException("Cannot parse '" + value + "' using format " + pattern,
					value, locale).setFormat(new SimpleDateFormat(pattern));
		}
	}

	@Override
	public String convertToString(final Object value, Locale locale){
		if (value == null){
			return null;
		}
		DateTime dt = new DateTime(((java.util.Date)value).getTime());
		return DateTimeFormat.forPattern(pattern).print(dt);
	}

	@Override
	protected Class<Time> getTargetType()
	{
		return Time.class;
	}
	
	public String getPattern() {
		return pattern;
	}

	public void setPattern(String pattern) {
		this.pattern = pattern;
	}

}